package ru.gelin.android.bells;

import java.util.List;

import ru.gelin.android.bells.timers.Timer;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AlarmActivity extends NowActivity implements Constants {

    /** Time (in millis) to show this activity */
    static final long SHOW_TIME = 55000;        //55 seconds
    //static final long SHOW_TIME = 10000;        //10 seconds
    /** Period (in millis) to check ringtone */
    static final int RINGTONE_TIME = 5000;  //5 seconds
    /** What property of a message to a ring handler */
    static final int RING_WHAT = 0;
    
    /** Storage of the timers */
    TimerStorage timers;
    /** Ringtones to play */
    RingtoneList ringtones;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm);
        timers = TimerStorage.getInstance(this);
        
        Button ok = (Button)findViewById(R.id.ok_button);
        ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        
        setVolumeControlStream(AudioManager.STREAM_ALARM);
        
        if (savedInstanceState == null) {   //first start
            if (isPlaying() && loadAlarms()) {
                ringtones.playNext();
                ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME);
            } else {
                finish();   //immediately close activity
                Intent intent = new Intent(this, TimersListActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);  //open timers list
            }
        } else {    //restart
            loadAlarms();
        }

        TextView time = (TextView)findViewById(R.id.alarm_time);
        time.setText(getResources().getString(R.string.alarm_time, now));
    }

    @Override
    public void onStop() {
        super.onStop();
        if (ringtones != null) {
            ringtones.stop();
        }
    }

    /**
     *  Finished the activity. Updates timer's list to the next alarm.
     */
    @Override
    public void finish() {
        super.finish();
        ringHandler.removeMessages(RING_WHAT);
        timers.normalize(now);
        timers.scheduleAlarm(now);
        timers.save();
    }
    
    /**
     *  Loads list of alarms.
     *  @return false if there is no alarms
     */
    boolean loadAlarms() {
        timers.load();
        List<Timer> alarms = timers.selectAlarms(now);
        if (alarms.size() == 0) {
            return false;
        }
        ListView list = (ListView)findViewById(R.id.alarms_list);
        ListAdapter adapter = new AlarmsListAdapter(this, alarms, now);
        list.setAdapter(adapter);
        ringtones = new RingtoneList(this, alarms);
        return true;
    }
    
    /**
     *  Returns true if we should still play alarm and display timers descriptions.
     *  Returns false if we should not, i.e. 50 seconds came from the
     *  start of the activity.
     */
    boolean isPlaying() {
        return now != null && 
                System.currentTimeMillis() <= now.getTime() + SHOW_TIME;
    }
    
    /**
     *  Handles ringtone playing. Restarts ringtone if it stops.
     */
    final Handler ringHandler = new Handler() {
        public void handleMessage(Message msg) {
            ringtones.playNext();
            if (isPlaying()) {
                ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME);
            } else {
                finish();
            }
        };
    };

}
